package cn.hubujyjs.mooc.service.impl;

import cn.hubujyjs.mooc.entity.Teacher;
import cn.hubujyjs.mooc.mapper.TeacherMapper;
import cn.hubujyjs.mooc.service.TeacherService;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 讲师 服务实现类
 * </p>
 *
 * @author Huang Jintao
 * @since 2022-11-15
 */
@Service
public class TeacherServiceImpl extends ServiceImpl<TeacherMapper, Teacher> implements TeacherService {
    public static final String MOOC_TEACHER_CACHE="mooc:teacher:cache:";
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    public void saveTeacher(Teacher teacher) {
        this.save(teacher);
        redisTemplate.delete(MOOC_TEACHER_CACHE+teacher.getId());
    }

    @Override
    @Transactional
    public Teacher getTeacherById(Long id) {
        String s = redisTemplate.opsForValue().get(MOOC_TEACHER_CACHE + id);
        if (StrUtil.isNotEmpty(s)){
            return JSONUtil.toBean(s, Teacher.class);
        }
        Teacher byId = this.getById(id);
        String jsonTeacher = JSONUtil.toJsonStr(byId);
        redisTemplate.opsForValue().set(MOOC_TEACHER_CACHE+id,jsonTeacher);
        return byId;
    }
}
